package org.yn.auth.intercepter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yn.base.util.AjaxResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");

        //如果token为空,说明未登录,要返回错误信息并拦截
        if(StringUtils.isBlank(token)){
            AjaxResult ajaxResult = AjaxResult.error("noLogin");
            response.getWriter().print(JSONObject.toJSONString(ajaxResult));
            return false;
        }

        // 根据token作为key,去redis中获取登录信息
        Object obj = redisTemplate.opsForValue().get(token);

        // 如果登录信息为空,说明未登录,要返回错误信息并拦截
        if(Objects.isNull(obj)){
            AjaxResult ajaxResult = AjaxResult.error("noLogin");
            response.getWriter().print(JSONObject.toJSONString(ajaxResult));
            return false;
        }

        // 如果不为空,说明已经登录过就放行,
        // 重新给token设置时间
        redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
        return true;
    }
    

}
